package jwei.apps.indextank.adapters;

import jwei.apps.indextank.R;
import jwei.apps.indextank.db.IngredientDb;
import jwei.apps.indextank.db.RestaurantCache.RestaurantsCache;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class RestaurantsCursorAdapter extends SimpleCursorAdapter {

    private int layout;

    public RestaurantsCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.layout = layout;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(layout, parent, false);
        return v;
    }

    @Override
    public void bindView(View v, Context context, Cursor c) {
        String productName = c.getString(c.getColumnIndex(RestaurantsCache.NAME));
        String brandName = c.getString(c.getColumnIndex(RestaurantsCache.STREET));

        // check if ingredients list matches users
        String ing = c.getString(c.getColumnIndex(RestaurantsCache.INGREDIENTS));
        boolean hasIng = false;
        String[] ingredients = ing.split(",");
        IngredientDb idb = IngredientDb.getInstance();
        for (String ingredient : ingredients) {
            ingredient = ingredient.trim();
            if (idb.isCached(context.getContentResolver(), ingredient)) {
                hasIng = true;
                break;
            }
        }

        TextView prodText = (TextView) v.findViewById(R.id.restaurant_name);
        TextView brandText = (TextView) v.findViewById(R.id.restaurant_street);
        ImageView ingImage = (ImageView) v.findViewById(R.id.ingredient_active);

        prodText.setText(productName);
        brandText.setText(brandName);

        if (hasIng) {
            ingImage.setBackgroundResource(R.drawable.wheat);
        } else {
            ingImage.setBackgroundResource(0);
        }
    }

}
